<template>
  <view class="order-page">
    <view class="nav-bar">
      <view
        class="nav-item-card"
        :class="{'nav-item-active': currentTab === 'all'}"
        @click="changeTab('all')"
      >
        全部
      </view>
      <view
        class="nav-item-card"
        :class="{'nav-item-active': currentTab === 'unpaid'}"
        @click="changeTab('unpaid')"
      >
        待支付
      </view>
      <view
        class="nav-item-card"
        :class="{'nav-item-active': currentTab ==='shipping'}"
        @click="changeTab('shipping')"
      >
        运输中
      </view>
      <view
        class="nav-item-card"
        :class="{'nav-item-active': currentTab ==='received'}"
        @click="changeTab('received')"
      >
        待评价
      </view>
    </view>
    <view class="order-list">
      <view
        v-for="(order, index) in filteredOrderList"
        :key="index"
        class="order-item"
      >
        <view class="order-info">
          <view class="order-header">
            <text class="order-number">订单号: {{ order.id }}</text>
            <!-- 新增显示店铺名 -->
            <text class="order-shop-name">店铺: {{ getShopName(order) }}</text>
          </view>
        </view>
        <view class="order-content">
          <view class="order-products">
            <view
              v-for="(product, productIndex) in order.products || []"
              :key="productIndex"
              class="product-item"
            >
              <view class="product-image-info">
                <image :src="product.imgUrl" mode="aspectFill"></image>
                <view class="product-details">
                  <text class="product-name">{{ product.name }}</text>
                  <text class="product-quantity">数量: {{ product.quantity }}</text>
                  <text class="product-price">￥{{ product.price * product.quantity }}</text>
                </view>
              </view>
            </view>
          </view>
          <view class="order-actions">
            <button v-if="order.orderStatus === '待支付'" @click="goToPay(order.id)">
              去支付
            </button>
            <button v-if="order.orderStatus === '运输中'" @click="receiveGoods(order.id)">
              收货
            </button>
            <button v-if="order.orderStatus === '待评价'" @click="goToReview(order.id)">
              待评价
            </button>
            <button v-if="order.orderStatus === '已评价'" disabled>
              已评价
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      orderList: [],
      currentTab: 'all',
    };
  },
  computed: {
    filteredOrderList() {
      switch (this.currentTab) {
        case 'all':
          console.log('All orders:', this.orderList);
          return this.orderList;
        case 'unpaid':
          const unpaidOrders = this.orderList.filter(order => order.orderStatus === '待支付');
          console.log('Unpaid orders:', unpaidOrders);
          return unpaidOrders;
        case'shipping':
          const shippingOrders = this.orderList.filter(order => order.orderStatus === '运输中');
          console.log('Shipping orders:', shippingOrders);
          return shippingOrders;
        case'received':
          const receivedOrders = this.orderList.filter(order => order.orderStatus === '待评价');
          console.log('Received (to be reviewed) orders:', receivedOrders);
          return receivedOrders;
        default:
          console.log('Default orders:', this.orderList);
          return this.orderList;
      }
    }
  },
  created() {
    this.fetchOrderData();
  },
  methods: {
    async fetchOrderData() {
      try {
        const response = await axios.get('http://localhost:3000/order');
        this.orderList = response.data;
        console.log('Fetched order data:', this.orderList);
      } catch (error) {
        console.error('获取订单数据失败:', error);
      }
    },
    changeTab(tab) {
      this.currentTab = tab;
    },
    goToPay(orderId) {
      uni.navigateTo({
        url: `/pages/order/orderpay?orderId=${orderId}`
      });
    },
    async receiveGoods(orderId) {
      if (!orderId) {
        uni.showToast({
          title: '订单信息有误，请重试',
          icon: 'none'
        });
        return;
      }
      uni.showLoading({
        title: '正在收货...'
      });
      try {
        const originalOrderResponse = await axios.get(`http://localhost:3000/order/${orderId}`);
        const originalOrder = originalOrderResponse.data;
        const updatedOrder = {
          ...originalOrder,
          orderStatus: '待评价'
        };
        const response = await axios.put(`http://localhost:3000/order/${orderId}`, updatedOrder);
        this.fetchOrderData();
        uni.hideLoading();
        uni.showToast({
          title: '收货成功',
          icon:'success'
        });
      } catch (error) {
        console.error('收货操作失败', error);
        uni.hideLoading();
        uni.showToast({
          title: '收货失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    async goToReview(orderId) {
      if (!orderId) {
        uni.showToast({
          title: '订单信息有误，请重试',
          icon: 'none'
        });
        return;
      }
      uni.showLoading({
        title: '正在提交评价...'
      });
      try {
        const originalOrderResponse = await axios.get(`http://localhost:3000/order/${orderId}`);
        const originalOrder = originalOrderResponse.data;
        const updatedOrder = {
          ...originalOrder,
          orderStatus: '已评价'
        };
        const response = await axios.put(`http://localhost:3000/order/${orderId}`, updatedOrder);
        this.fetchOrderData();
        uni.hideLoading();
        uni.showToast({
          title: '评价成功',
          icon:'success'
        });
      } catch (error) {
        console.error('评价操作失败', error);
        uni.hideLoading();
        uni.showToast({
          title: '评价失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    // 新增方法用于获取店铺名
    getShopName(order) {
      if (order.products && order.products.length > 0) {
        return order.products[0].shopName;
      }
      return '未知店铺';
    }
  }
};
</script>

<style scoped>
page {
  background-color: #f8f8f8;
}

/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.order-page {
  padding: 30px 20px;
  background-color: #f9f9f9;
  font-family: 'Roboto', sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-bar {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
}

.nav-item-card {
  padding: 15px 30px;
  border-radius: 15px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
  text-align: center;
}

.nav-item-card:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.nav-item-active {
  color: white;
  background-color: #007bff;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-3px);
}

.order-list {
  width: 100%;
  max-width: 800px;
}

.order-item {
  background-color: white;
  padding: 25px;
  border-radius: 12px;
  margin-bottom: 25px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: all 0.3s ease;
}

.order-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.order-info {
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-number {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.order-shop-name {
  font-size: 16px;
  color: #666;
}

.order-time {
  font-size: 16px;
  color: #999;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-products {
  display: flex;
  flex-wrap: wrap;
}

.product-item {
  width: 100%;
  margin-right: 20px;
  margin-bottom: 20px;
  text-align: left;
  display: flex;
  background-color: #f9f9f9;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.product-item:hover {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.product-image-info {
  display: flex;
  align-items: center;
}

.product-item image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
  margin-right: 15px;
}

.product-details {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.product-quantity {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.product-price {
  font-size: 14px;
  color: #e74c3c;
}

.order-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.order-actions button {
  padding: 12px 25px;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.3s ease;
  margin-bottom: 10px;
}

.order-actions button:nth-child(1) {
  background-color: #3498db;
}

.order-actions button:nth-child(1):hover {
  background-color: #2980b9;
}

.order-actions button:nth-child(2) {
  background-color: #3498db;
}

.order-actions button:nth-child(2):hover {
  background-color: #2980b9;
}

.order-actions button:nth-child(3) {
  background-color: #3498db;
}

.order-actions button:nth-child(3):hover {
  background-color: #2980b9;
}
</style>